package com.matrix.java.chap_06;

import java.time.LocalDate;
import java.time.LocalDateTime;

/*
    显示当前日期和时间
 */
public class Ex6_24 {
    public static void main(String[] args) {
        System.out.println(LocalDateTime.now());
        //获取至今的毫秒数
        long totalMilliSeconds = System.currentTimeMillis();
        //转化为秒数
        long totalSeconds = totalMilliSeconds / 1000;
        long currentSecond = totalSeconds % 60;
        //转化为分钟数
        long totalMinutes = totalSeconds / 60;
        long currentMinute = totalMinutes % 60;
        //转化为小时数
        long totalHours = totalMinutes / 60;
        long currentHour = totalHours % 24;
        //转化为天数
        long totalDays = totalHours / 24;
        if (currentHour > 0) {
            totalDays++;
        }

        long currentYear = 2000;
        do {
            currentYear++;
        } while (getTotalDaysInYears(currentYear) < totalDays);
        long totalNumOfDaysInTheYear = totalDays - getTotalDaysInYears(currentYear - 1);

        long currentMonth = 0;
        do {
            currentMonth++;
        } while (getTotalDaysInMonths(currentYear, currentMonth) < totalNumOfDaysInTheYear);
        long currentDay = totalNumOfDaysInTheYear - getTotalDaysInMonths(currentYear, currentMonth - 1);


        System.out.println(currentYear + "-" + currentMonth + "-" + currentDay + " " + currentHour + ":" + currentMinute + ":" + currentSecond);
    }

    private static long getTotalDaysInYears(long year) {
        long total = 0;
        for (int i = 1970; i <= year; i++) {
            if (isLeapYear(i)) {
                total += 366;
            } else {
                total += 365;
            }
        }
        return total;
    }
    private static long getTotalDaysInMonths(long year, long month) {
        long total = 0;
        for (int i = 1; i <=month ; i++) {
            total+=getNumOfDayDaysInMonth(year,i);
        }
        return total;
    }
    private static long getNumOfDayDaysInMonth(long year, long month) {
        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
            return 31;
        } else if (month == 4 || month == 6 || month == 9 || month == 11) {
            return 30;
        } else {
            if (isLeapYear(year)) {
                return 29;
            } else {
                return 28;
            }
        }
    }

    private static boolean isLeapYear(long year) {
        if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
            return true;
        }
        return false;
    }

}
